package com.zm.authority.realm.controller;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import com.zm.authority.identity.po.ZmUser;
import com.zm.authority.identity.service.IdentityService;
import com.zm.base.core.exception.BaseException;

/*import com.advio.acs.entity.identity.User;
import com.advio.acs.service.identity.IdentityService;*/

/**
 * UserAuthorizingRealm
 * @author DENG.ZHUO.HUI
 * @email 13751827792@163.com
 * @date 2017年2月10日
 * @version 1.0
 */
public class UserAuthorizingRealm extends AuthorizingRealm {
	@Resource(name="identityService")
	private IdentityService identityService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		//System.out.println("=============== Authorization ================");
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		Subject subject = SecurityUtils.getSubject();
		ZmUser user= (ZmUser) subject.getSession().getAttribute("user");
		try {
			//获取该用户的拥有的角色
			Set<String> roles = identityService.getRolesByUserId(user.getId());
			simpleAuthorizationInfo.setRoles(roles);
			if(null!=roles&&!"".equals(roles)){
				//获取该用户拥有的权限
				String[] roleArrays = roles.toArray(new String[] {}); 
				Set<String> permissions = identityService.getPermissionsByRoleIds(roleArrays);
				simpleAuthorizationInfo.setStringPermissions(permissions);
			}
		} catch (BaseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		ZmUser user=null;
		try {
			user = identityService.getUserByUserName(userName);
		} catch (BaseException e) {
			throw new UnknownAccountException("用户名不存在");
		} catch (Exception e) {
			throw new UnknownAccountException("用户名不存在");
		}
		if(user == null){
			throw new UnknownAccountException("用户名不存在");
		}
		return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),ByteSource.Util.bytes(user.getSalt()),this.getName());
		//return new SimpleAuthenticationInfo("admin","admin",ByteSource.Util.bytes("ead384af0516a94b9de70c95973e2211"),"");
	}

}
